package com.my.controller;


import com.alibaba.fastjson.JSONObject;
import com.my.pojo.PmsProduct;
import com.my.pojo.PmsSkuValue;
import com.my.pojo.PmsSpuValue;
import com.my.pojo.PmsStock;
import com.my.service.*;
import com.my.util.ResultJson;
import io.minio.errors.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author us
 * @since 2021-07-07
 */
@RestController
@RequestMapping("/pms-product")
public class PmsProductController {
    @Resource
    IPmsProductService productService;
    @Resource
    IPmsBrandService brandService;
    @Resource
    IPmsCategoryService categoryService;
    @Resource
    IPmsSpuService spuService;
    @Resource
    IPmsSkuService skuService;
    @Resource
    IImgService imgService;
    @Resource
    IPmsSpuValueService spuValueService;
    @Resource
    IPmsSkuValueService skuValueService;
    @Resource
    IPmsStockService stockService;



    @GetMapping("/getone")
    ResultJson getOne(Long id) {
        return ResultJson.success(productService.getById(id));
    }
    @GetMapping("/list")
    ResultJson list(Integer pageNo, Integer pageSize,String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("product",productService.page(pageNo,pageSize,name));
        map.put("brand",brandService.page(pageNo,pageSize,""));
       // map.put("category",categoryService.);
//        return ResultJson.success(productService.page(pageNo,pageSize,name));
        return ResultJson.success(map);
    }
    @GetMapping("/getData")
    ResultJson getData() {
        Map<String, List> map = new HashMap<>();
        map.put("brands",brandService.getAll());
        map.put("categorys",categoryService.getAll(0L));
        return ResultJson.success(map);
    }
    @GetMapping("/getAttr")
    ResultJson getAttr(Long[] categoryIds) {
        Map<String,List> map = new HashMap<>();
        map.put("spus",spuService.getByCategory(categoryIds));
        map.put("skus",skuService.getByCategory(categoryIds));
        return ResultJson.success(map);
    }
    @PostMapping("/add")
    @Transactional
    ResultJson add(PmsProduct pmsProduct, MultipartFile file, MultipartFile[] files,String[] spus, String[] skus,String[] stocks) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        pmsProduct.setImg(imgService.upload(file));
        List<String> piclist = new ArrayList<>();
        System.out.println("相册长度："+files.length);
        for(MultipartFile f : files) {
            piclist.add(imgService.upload(f));
        }
        pmsProduct.setPics(piclist.toString().replaceAll("\\[","").replaceAll("\\]",""));

        productService.save(pmsProduct);
        List<PmsSpuValue> spuValueList = new ArrayList<>();
        for(String spu : spus) {
            PmsSpuValue pmsSpuValue = JSONObject.parseObject(spu, PmsSpuValue.class);
            pmsSpuValue.setProductId(pmsProduct.getId());
            spuValueList.add(pmsSpuValue);
        }
        spuValueService.saveBatch(spuValueList);
        List<PmsSkuValue> skuValueList = new ArrayList<>();
        for(String sku : skus) {
            PmsSkuValue pmsSkuValue = JSONObject.parseObject(sku,PmsSkuValue.class);
            pmsSkuValue.setProductId(pmsProduct.getId());
            skuValueList.add(pmsSkuValue);
        }
        skuValueService.saveBatch(skuValueList);
        List<PmsStock> stockList = new ArrayList<>();
        for(String stock : stocks) {
            PmsStock pmsStock = JSONObject.parseObject(stock, PmsStock.class);
            pmsStock.setProductId(pmsProduct.getId());
            stockList.add(pmsStock);
        }
        stockService.saveBatch(stockList);
        return ResultJson.success("","添加成功");
    }
    @PostMapping("/update")
    ResultJson update(PmsProduct pmsProduct, MultipartFile file, MultipartFile[] files,String[] spus, String[] skus,String[] stocks) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        if(file != null && file.getSize() > 0) {
            pmsProduct.setImg(imgService.upload(file));
        }
        List<String> piclist = new ArrayList<>();
        for(MultipartFile f : files) {
            if(f != null && f.getSize() > 0) {
                piclist.add(imgService.upload(f));
            }
        }
        pmsProduct.setPics(piclist.toString().replaceAll("\\[","").replaceAll("\\]",""));
        productService.updateById(pmsProduct);
        return ResultJson.success("","修改成功");
    }


        @PostMapping("/del")
    ResultJson del(PmsProduct pmsProduct) {
        String message = pmsProduct.getActive() == 0 ? "删除商品成功" : "恢复商品成功";
//        skuValueService.removeById();
//        spuValueService.removeById();
//        stockService.removeById();
        //
//
//            List<PmsSpuValue> list = spuValueService.list();
//            for(PmsSpuValue p: list){
//                System.out.println(p.getId());
//            }
            Long id=pmsProduct.getId();



            List<PmsStock> stockList= stockService.list();
            List<PmsSkuValue> skuList= skuValueService.list();
            List<PmsSpuValue> spuList= spuValueService.list();

        for(PmsStock p:stockList){
            if(p.getProductId()==id){
                stockService.removeById(p.getId());
            }
        }
            for(PmsSkuValue p:skuList){
                if(p.getProductId()==id){
                    skuValueService.removeById(p.getId());
                }
            }
            for(PmsSpuValue p:spuList){
                if(p.getProductId()==id){
                    spuValueService.removeById(p.getId());
                }
            }
        return ResultJson.success(productService.removeById(pmsProduct.getId()),message);
    }
    @PostMapping("/off")
    ResultJson off(PmsProduct pmsProduct) {
        String message = pmsProduct.getPublishStatus() == 0 ? "下架商品成功" : "重新上架商品成功";
        return ResultJson.success(productService.updateById(pmsProduct),message);
    }
//    @GetMapping("/getBrandName")
//    ResultJson getBrandName(String id) {
//        try{return ResultJson.success(brandService.getById(id));}catch (Exception e){}
//        return null;
//    }
    @GetMapping("/getCategorName")
    ResultJson getCategorName(String id) {
        String lastId="";
            for (int i =id.length()-1;i>0;i--) {
                if (id.charAt(i) == ',') {
                    for (int j = i; j < id.length() - 1; j++) {
                        lastId = lastId + id.charAt(j + 1);
                    }
                    i = -1;
                }
            }
            return ResultJson.success(categoryService.getById(Integer.valueOf(lastId)));
    }
}
